const koa           = require('koa')
    , open          = require('open')
    , webpack       = require('webpack')
    , serve         = require('koa-static')
    , c2k           = require('koa-connect')
    , webpackConfig = require('./webpack.config')
    , HotMiddlewate = require('webpack-hot-middleware')
    , DevMiddleware = require('koa-webpack-dev-middleware')
    , history       = require('connect-history-api-fallback')
    ;

Object.keys(webpackConfig.entry).forEach((name)=> {
    webpackConfig.entry[name] = ['webpack-hot-middleware/client'].concat(webpackConfig.entry[name])
});
webpackConfig.devtool = '#source-map';
// hot reload 配置
webpackConfig.plugins.unshift(new webpack.NoErrorsPlugin());
webpackConfig.plugins.unshift(new webpack.HotModuleReplacementPlugin());
webpackConfig.plugins.unshift(new webpack.optimize.OccurenceOrderPlugin());

const app           = koa()
    , compiler      = webpack(webpackConfig)
    , devMiddleware = DevMiddleware(compiler, {
          publicPath: '/',
          noInfo: false,
          reload: true,
          stats: {
              color: true,
              chunks: false
          }
      })
    , hotMiddleware = HotMiddlewate(compiler)
    ;

compiler.plugin('compilation', (compilation)=> {
    compilation.plugin('html-webpack-plugin-after-emit', (data, cb)=> {
        hotMiddleware.publish({action: 'reload'});
        cb();
    })
});

// app.use(c2k(history()));
app.use(devMiddleware);
app.use(c2k(hotMiddleware));
app.use(serve('.'));

app.listen(3000, ()=> {
    open('http://localhost:3000');
});
